<?php
namespace app\admin\validate;
use app\admin\code\AdminCode;
use app\admin\model\BaseModel;
use think\Lang;
use think\Validate;

class BaseValidate
{
    /**
     * @var array 验证规则
     */
    protected $_rule = [];
    /**
     * @var array 错误时返回的信息
     */
    protected $_message = [];
    /**
     * @var array 验证场景
     */
    protected $_scene = [];
    /**
     * @var array 扩展验证规则
     */
    protected $_extend_rule = [];
    /**
     * @var array 扩展规则对应方法
     */
    protected $_extend_fun = [];
    /**
     * @var string 错误信息
     */
    private $_error_msg = '';
    /**
     * @BaseModel 验证数据需要用到的模型
     */
    protected $_model;
    /**
     * @array 从_model中查出的数据
     */
    protected $_db_data;
    /**
     * @var array 别名
     */
    protected $_field = [];
    public function __construct(BaseModel $model)
    {
        $this->_model = $model;
    }

    public function validate(array $param, $scene){
        if(!isset($scene,$this->_scene)){
            return true;
        }
        $this->_register_extend_fun();
        $this->_extend_validate();
        $validate = new Validate([],[],$this->_field);
        $validate->message($this->_message);
        $validate->scene($this->_scene);
        if($validate->check($param,$this->_rule,$scene) === false){
            $this->_error_msg = $validate->getError();
            return false;
        }else{
            return true;
        }

    }

    /**
     * 设置扩展验证
     */
    protected function _extend_validate(){
        if(count($this->_extend_rule) > 0){
            foreach ($this->_extend_rule as $value){
                Validate::extend($value,$this->_extend_fun[$value]);
            }
        }
    }
    /**
     * 注册扩展验证方法
     */
    protected function _register_extend_fun(){
        $_self = $this;
        foreach ($this->_extend_rule as $value){
            $this->_extend_fun[$value] = function($data)use($_self,$value){
                return $_self->$value($_self,$data);
            };
        }
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError(){
        $lang = Lang::get();
        $code = array_search($this->_error_msg,$lang);
        $msg = $this->_error_msg;
        return ['msg'=>$msg,'code'=>$code];
    }
    public function get_db_data(){
        return $this->_db_data;
    }
}


